<?php
declare (strict_types=1);

namespace app\course\service\live\admin;

use app\common\logic\category\admin\Category;
use app\common\service\BaseService;
use app\course\logic\live\admin\LiveSmall as LiveLogic;
use app\course\logic\live\admin\LiveSmallSection as SectionLogic;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\libs\pagelist\ListItem;
use eduline\admin\page\PageForm;
use eduline\admin\page\PageList;
use think\annotation\Inject;
use think\facade\Request;

/**
 * 小班课程接口类-后台
 */
class LiveSmall extends BaseService
{
    /**
     * @Inject()
     *
     * @var LiveLogic
     */
    protected $liveLogic;

    /**
     * 列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-23
     *
     * @return   [type]                         [description]
     */
    public function index()
    {
        $mhmId = Request::get('mhm_id/d', request()->mhm_id);
        // 搜索功能
        $map = [];
        Request::has('mhm_id', 'get', true) && $map[] = ['mhm_id', '=', Request::get('mhm_id/d')];
        Request::has('title', 'get', true) && $map[] = ['title', 'like', '%' . Request::get('title/s') . '%'];
        $category = Request::get('category/d', 0);
        if ($category && $mhmId === 1) {
            $map[] = ['category', 'like', '%,' . $category . ',%'];
            $map[] = ['mhm_id', '=', $mhmId];
        } else if ($category) {
            $map[] = ['mhm_category', 'like', '%,' . $category . ',%'];
        }
        if (Request::has('status', 'get', true) && Request::get('status/d', -1) !== -1) {
            $map[] = ['status', '=', Request::get('status/d')];
        } else {
            // 搜索功能
            $map[] = ['status', 'in', '0,1'];
        }

        // 推荐课程
        if (Request::get('is_recommend/d', 0) == 1) {
            $map[] = ['is_recommend', '=', 1];
        }

        $data        = $this->liveLogic->liveList($map);
        $is_platform = request()->is_platform;
        // 定义字段
        $keyList = [
            'title'         => ListItem::make('custom')->title('名称')->width(140),
            'school_name'   => ListItem::make()->title('机构')->visible($is_platform),
            'cates'         => ListItem::make('custom')->title('分类')->width(142),
            'teacher_name'  => ListItem::make()->title('讲师'),
            'status'        => ListItem::make('custom')->title('上架状态')->width(40),
            'is_recommend'  => ListItem::make('custom')->title('推荐课程')->width(40),
            // 'credit_redeem' => ListItem::make('custom')->title('积分抵扣购买')->width(40),
            'update_status' => ListItem::make('custom')->title('连载状态'),
            'create_time'   => ListItem::make()->title('创建时间'),
            'update_time'   => ListItem::make()->title('更新时间')
        ];
        // 课程分类
        $category  = app(Category::class)->cascaderCate();
        $searchKey = [
            'mhm_id'   => FormItem::make('searchSchool')->title(false)->visible($is_platform),
            'title'    => FormItem::make('input')->title(false)->placeholder('名称')->maxlength(30),
            'category' => FormItem::make('cascader')->title(false)->options($category)->placeholder('分类')->required(),
            'status'   => FormItem::make('select')->title(false)->placeholder('状态')->options([
                ['title' => '不限制', 'value' => -1],
                ['title' => '已上架', 'value' => 1],
                ['title' => '已下架', 'value' => 0],
            ]),
        ];
        // 设置表单
        $list = app(PageList::class);
        // 表单字段
        $list->pageKey   = $keyList;
        $list->searchKey = $searchKey;
        $list->datas     = $data;

        return $list->send();
    }

    /**
     * 创建课程
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-15
     *
     * @param Request $request [description]
     * @return   [type]                                  [description]
     */
    public function create()
    {
        if (Request::isPost()) {
            $data = Request::post();
            $re   = $this->liveLogic->addLive($data);

            return $this->parseToData($re->toArray(), 1, '添加成功');
        }
        /* 创建课程界面配置 */
        $keyList = $this->keyListInit(false, 'create');
        // 设置表单
        $form = app(PageForm::class);
        // 表单字段
        $form->pageKey = $keyList;
        // 排序
        // $form->pageKeySort = ['mhm_id'];
        $form->saveMethod  = 'POST';
        $form->savePostUrl = 'course/admin/live/small/create';

        return $form->send();

    }

    /**
     * 修改课程信息
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-15
     */
    public function update($id)
    {
        if (Request::isPut()) {
            $data = Request::put();
            $live = LiveLogic::where('id', $id)->findOrFail();
            $live = $this->liveLogic->editLive($live, $data);

            return $this->parseToData($live->toArray(), 1, '编辑成功');
        }

        $data            = $this->liveLogic->with(['cover_url', 'school'])->findOrFail($id);
        $data->cates     = $data->fullcategorypath;
        $data->mhm_cates = $data->mhm_fullcategorypath;
        $teacher         = $data->teacher;
        if ($teacher) {
            $data->teacher_name = $teacher->nick_name;
        }

        // 有效期处理
        if ($termTime = $data->getAttr('term_time')) {
            if ($termTime <= 9999) {
                $data->term_time = ['type' => 1, 'days' => $termTime];
            } else {
                $data->term_time = ['type' => 2, 'date' => date('Y-m-d', $termTime)];
            }
        }

        // 查询是否有课时,添加课时后不允许更改目录结构
        $disbaleLevel = (boolean)SectionLogic::where('course_id', $id)->value('id');
        // 创建课程界面配置
        $keyList = $this->keyListInit($disbaleLevel, 'edit', $data->mhm_id);
        // 设置表单
        $form = app(PageForm::class);
        // 表单字段
        $form->datas       = $data;
        $form->pageKey     = $keyList;
        $form->saveMethod  = 'PUT';
        $form->savePostUrl = '/course/admin/live/small/' . $id;

        return $form->send();
    }

    /**
     * 课程界面配置
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-26
     */
    public function keyListInit($disbaleLevel = false, $action = 'create', $mhm_id = '')
    {
        $is_platform       = request()->is_platform;
        $platform_category = app(Category::class)->platformCascaderCate();
        // 课程层级
        $section_level = [
            ['title' => '一级', 'value' => 1],
            ['title' => '二级', 'value' => 2],
            ['title' => '三级', 'value' => 3],
        ];

        $mhm_id       = $is_platform ? $mhm_id : request()->user->mhm_id;
        $mhm_category = [];
        if (!$is_platform) {
            // 不是平台的时候,获取机构的分类
            $mhm_category = app(Category::class)->cascaderCate();
        }

        // 定义字段
        $keyList = [
            'mhm_id'                => FormItem::make('searchSchool')->title('机构')->required()->visible($is_platform),
            'teacher_id'            => FormItem::make('custom')->title('讲师')->required()->mhm_id($mhm_id),
            'cates'                 => FormItem::make('cascader')->title('平台课程分类')->options($platform_category)->multiple(true),
            'mhm_cates'             => FormItem::make('cascader')->title('机构课程分类')->options($mhm_category)->multiple(true)->visible(!$is_platform),
            'title'                 => FormItem::make()->title('课程名称')->maxlength(100)->required(),
            'section_level'         => FormItem::make('select')->title('目录层级')->help('1. 确定课程目录结构，如三级【章-节-课】 <br />2. 课程添加课时后将不允许更改目录层级')->options($section_level)->disabled($disbaleLevel)->required(),
            'cover'                 => FormItem::make('custom')->title('课程封面')->limit(1)->required()->help('建议宽高尺寸为412px*228px'),
            'info'                  => FormItem::make('editor')->title('简介'),
            'listing_time'          => FormItem::make('date')->title('上架时间')->dateType(FormItem::option('DateType', 'DATETIME'))->format('yyyy-MM-dd HH:mm')->required(),
            'scribing_price'        => FormItem::make('inputNumber')->title('原价')->min(0)->max(9999999)->precision(2),
            'price'                 => FormItem::make('inputNumber')->title('售价')->min(0)->max(9999999)->precision(2)->required(),
            'vip_price'             => FormItem::make('custom')->title('会员价')->help('为0时表示会员免费'),
            'sale_count_market'     => FormItem::make('inputNumber')->title('营销量')->min(0)->help('虚拟购买量，用于营销'),
            'limit_buy_count'       => FormItem::make('inputNumber')->title('购买人数')->min(1)->max(15)->required()->help('最多支持15人'),
            'give_credit'           => FormItem::make('inputNumber')->title('赠送积分')->min(0),
            'comment_credit'        => FormItem::make('inputNumber')->title('评论赠送积分')->min(0),
            'share_credit'          => FormItem::make('inputNumber')->title('分享赠送积分')->min(0),
            'credit_redeem'         => FormItem::make('slideSwitch')->title('积分抵扣购买')->activeValue(1)->inactiveValue(0),
            'credit_redeem_percent' => FormItem::make('inputNumber')->title('最高抵扣比例')->min(0)->max(100)->help('可抵扣订单金额的百分比'),
            // 'status'          => FormItem::make('slideSwitch')->title('状态')->activeValue(1)->inactiveValue(0)->visible($action == 'edit'),
            // 'is_recommend'    => FormItem::make('slideSwitch')->title('推荐课程')->activeValue(1)->inactiveValue(0),
            // 'open_comment'    => FormItem::make('slideSwitch')->title('开启评论')->activeValue(1)->inactiveValue(0),
            'solo'                  => FormItem::make('slideSwitch')->title('是否允许单卖')->activeValue(1)->inactiveValue(0)->help('仅支持不允许单卖的课程添加到班级课'),
            'term_time'             => FormItem::make('custom')->title('课程有效期')->help('课程购买后有效天数，0表示不限制'),
            'exam_condition_rate'   => FormItem::make()->title('考试条件')->slot('%')->css(['width' => '126px'])->help('1. 需学完课程的百分比，达标后才可考试<br />2. 0表示不学习课程可直接考试'),

        ];

        return $keyList;
    }

    /**
     * 编辑指定的字段
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-27
     */
    public function editField($id, $field)
    {
        $value = Request::put($field);
        $video = $this->liveLogic->editField($id, $field, $value);

        return $this->parseToData($video, 1, '编辑成功');
    }

    /**
     * 删除课程
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-15
     */
    public function delete($id)
    {
        $this->liveLogic->deleteLive($id);

        return $this->parseToData([], 1, '删除成功');

    }

    public function sectionFinish($id)
    {
        $res = $this->liveLogic->sectionFinish($id);

        return $this->parseToData($res, 1, '完结成功');
    }

    /**
     * 批量上架
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/16
     *
     * @return \think\Response
     */
    public function listing()
    {
        $ids = Request::put('ids');
        $this->liveLogic->listingVideos($ids);

        return $this->parseToData([], 1, '操作成功');
    }

    /**
     * 批量禁用
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/16
     *
     * @return \think\Response
     */
    public function disables()
    {
        $ids = Request::put('ids');
        $this->liveLogic->disableVideos($ids);

        return $this->parseToData([], 1, '操作成功');
    }

    /**
     * 批量删除
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/16
     *
     * @return \think\Response
     */
    public function deletes($ids)
    {
        $this->liveLogic->deleteVideos($ids);

        return $this->parseToData([], 1, '操作成功');
    }
}
